<template>
  <div>
    <!-- 复选框 -->
    <el-checkbox-group v-model="checkList">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>
    <!-- 确定和取消按钮 -->
    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="setRoles">确定</el-button>
        <el-button size="small" @click="cancleDialog">取消</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getRoles } from '@/api/setting'
import { getUserDetailById } from '@/api/user'
import { assignRoles } from '@/api/employees'
export default {
  name: 'AssignRole',
  props: {
    userId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      checkList: [], // 选择后的数组
      roleList: [] //
    }
  },
  created() {
    //   获取角色列表
    this.getRoles()
    // 获取id
    this.getUserDetailById()
  },
  methods: {
    //   点击确定 分配权限
    async setRoles() {
      const res = await assignRoles({ id: this.userId, roleIds: this.checkList })
      this.$message.success(res.message)
      this.$emit('closure')
    },
    // 获取id
    async getUserDetailById() {
      const res = await getUserDetailById(this.userId)
      //   console.log(res)
      // 判断后端返回的 roleIds 是否为 null，如果为 null，说明没有角色，返回空数组即可
      // 如果不为 null，直接将角色列表返回
      this.checkList = res.data.roleIds === null ? [] : res.data.roleIds
    },
    //   获取角色列表
    async getRoles() {
      const res = await getRoles()
      this.roleList = res.data.rows
    //   console.log(res)
    },
    //   取消按钮
    cancleDialog() {
      this.$emit('closure')
    }
  }
}
</script>

<style >
.footer{
    margin-top: 30px;
}
</style>
